package com.nxmu.action;

import com.nxmu.entity.User;
import com.nxmu.enums.Role;
import com.nxmu.service.UserService;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.StringUtils;

public class UserController extends BaseAction implements ModelDriven<User> {

//    @Autowired
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    private User user;

    /**
     * 提示信息
     */
    private String tip;

    public String getTip() {
        return tip;
    }

    /**
     * 确认密码
     */
    private String pwd;

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    /**
     * 登陆
     * @return
     */
    public String login(){
        User login = userService.login(user);
        if (login != null){
            session.put("user",login);
            if ( login.getRole() != null && login.getRole().equals(Role.TEACHER)) return "teacher_entering";
            if ( login.getRole() != null && login.getRole().equals(Role.RESEARCH)) return "research";
            if ( login.getRole() != null && login.getRole().equals(Role.OFFICE)) return "office";
        }
        session.put("user",null);
        return LOGIN;
    }

    /**
     * 注册
     * @return
     */
    public String register(){
        //注册前先检查该用户是否已经存在
        if (userService.checkUserExist(user)){
            tip = "该用户名已经存在";
            request.put("tip",tip);
            return "registerError";
        }
        if (StringUtils.isNotBlank(pwd) && user.getPassword().equals(pwd)){
            tip = "注册成功！";
            userService.register(user);
            return LOGIN;
        }else {
            tip = "密码输入不一致";
            return LOGIN;
        }
    }

    @Override
    public User getModel() {
        user = new User();
        return user;
    }
}
